package cn.zdsoft.configuration.core;

import cn.zdsoft.configuration.core.api.CallbackAble;
import cn.zdsoft.configuration.core.exceptions.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 统一回调处理
 * Created by wangdongdong on 2018/5/16 11:00.
 */
public abstract class AbstractCallbackAble implements CallbackAble {

    private static final Logger logger = LoggerFactory.getLogger(AbstractCallbackAble.class);

    private ConfigContext configContext;

    private Properties properties;

    @Override
    public void init(ConfigContext context, Properties properties) {
        this.configContext = context;
        this.properties = properties;
    }

    @Override
    public void onChange(String key, String originValue, String newValue) throws ConfigurationException {
        logger.info("==========================>the key '{}' has changed from '{}' to '{}'", key, originValue, newValue);
        properties.put(key, newValue);

        if (!doOnChange(key, originValue, newValue, properties)) {
            throw ConfigurationException.createExceptin("===============>Error in callback processing");
        }
    }

    public abstract boolean doOnChange(String key, String originValue, String newValue, Properties properties) throws ConfigurationException;

    @Override
    public void onAdd(String key, String value) {

    }

    @Override
    public ConfigContext getConfigContext() {
        return configContext;
    }
}
